<?php
// src/Asiah/SiklusBundle/Controller/HomeController.php
namespace Asiah\SiklusBundle\Controller;

use Asiah\SiklusBundle\Entity\Link;
use Asiah\SiklusBundle\Entity\Bookmark;
use Asiah\SiklusBundle\Repository\LinkRepository;
use Asiah\SiklusBundle\Model\LinkLogic;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class HomeController extends Controller {
		
	public function indexAction(Request $request) {
		if($request -> getMethod() == 'POST') {
	   		$input = $request->request->get('url');  
			return $this->saveLink($input);
		}
		else if ($request -> getMethod() == 'GET')
		{
			$nilai = $request->query->get('url');
			if ($nilai!='')
			{
				//echo 'ini lho nilainya '.$nilai;
				return $this->saveLink($nilai);
			}
		}
		$parameter = array ('result'=>false);
		return $this -> render('AsiahSiklusBundle:Home:index.html.twig',$parameter);
	}
	private function saveLink($input)
	{
		$repolink = $this->getDoctrine()->getEntityManager()->getRepository('AsiahSiklusBundle:Link'); 
		$logic = new LinkLogic();
		$validate = $logic->validateURL($input);
		if ($validate){ 
			$hasil = $repolink->createOrReadLink($input);
			$this->get('session')->set('url',$hasil->getRealLink());
			return $this -> render('AsiahSiklusBundle:Home:index.html.twig',array('result'=>'benar', 'short'=>$hasil->getShortLink()));
		}
		else
			return $this -> render('AsiahSiklusBundle:Home:index.html.twig',array('result'=>'error', 'short'=>"errornya"));
	}
}
